package com.shareyi.springcore.scan;

import com.shareyi.springcore.annotation.CustomizeComponent;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.util.Map;
import java.util.Set;

/**
 * Created by david on 2017/5/14.
 */
public class MyScanner extends ClassPathBeanDefinitionScanner {



    public MyScanner(BeanDefinitionRegistry registry) {
        super(registry);

        final BeanNameGenerator defaultNameGnerator=new AnnotationBeanNameGenerator();
        setBeanNameGenerator(new BeanNameGenerator() {
            public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {

                String beanName=null;
                AnnotatedBeanDefinition annotatedBeanDefinition= (AnnotatedBeanDefinition) definition;
               Map<String,Object> annotation=annotatedBeanDefinition.getMetadata().getAnnotationAttributes(CustomizeComponent.class.getName(),true);
               if(annotation!=null && !annotation.isEmpty()){
                    beanName=(String) annotation.get("value");
               }

               if(beanName==null || beanName.length()==0){
                   beanName=defaultNameGnerator.generateBeanName(definition,registry);
               }
               return beanName;
            }
        });
    }


    /**
     * 添加自定义注解
     */
    public void registerDefaultFilters() {
        this.addIncludeFilter(new AnnotationTypeFilter(CustomizeComponent.class));
    }

    public Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
        for (BeanDefinitionHolder holder : beanDefinitions) {
            GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();
         //   definition.getPropertyValues().add("innerClassName", definition.getBeanClassName());
        }
        return  beanDefinitions;
    }


    /**
     * 是否备选的component，这里需要满足不是接口和抽象类， 并且加了CustomizeComponent注解
     * @param beanDefinition
     * @return
     */
    public boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        return super.isCandidateComponent(beanDefinition) && beanDefinition.getMetadata()
                .hasAnnotation(CustomizeComponent.class.getName());
    }
}
